<template>
  <el-dialog
    v-el-drag-dialog
    :title="type === 'add' ? '新增用户' : '编辑用户'"
    :visible.sync="visible"
    width="750px"
    class="addUser"
    @closed="reset"
  >
    <el-tabs v-if="visible" v-model="activeName" type="card">
      <el-tab-pane label="基本信息" name="basic">
        <el-form
          ref="dataForm"
          class="form"
          :rules="rules"
          :model="temp"
          label-position="right"
          label-width="100px"
        >
          <el-form-item label="编码:" prop="userCode">
            <el-input
              v-model.trim="temp.userCode"
              placeholder="手工输入或自动产生"
              :maxlength="userInfo.userId === 0 ? 10 : 20"
              :disabled="type === 'edit'"
              clearable
            >
              <el-button
                v-if="type === 'add'"
                slot="append"
                type="primary"
                size="small"
                plain
                @click.prevent="getOrgCode"
              >获取</el-button>
            </el-input>
          </el-form-item>
          <el-form-item v-if="type === 'add'" label="初始密码" prop="pwd">
            <el-input v-model.trim="temp.pwd" type="password" clearable />
          </el-form-item>
          <el-form-item label="名称:" prop="userName">
            <el-input
              v-model.trim="temp.userName"
              clearable
              :maxlength="11"
              show-word-limit
            />
          </el-form-item>
          <el-form-item label="类型:" prop="utype">
            <el-select
              v-model="temp.utype"
              multiple
              filterable
              placeholder="请选择"
              style="width: 100%;"
              clearable
            >
              <el-option
                v-for="item in filterUserTypeMap"
                :key="item.value"
                :label="item.desc"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="性别:" prop="usex">
            <el-select v-model="temp.usex">
              <el-option label="男" :value="1" />
              <el-option label="女" :value="2" />
            </el-select>
          </el-form-item>
          <el-form-item
            v-if="type === 'edit'"
            class="block"
            label="所属机构"
            prop="orgId"
          >
            <el-tree-select
              v-model="temp.orgId"
              class="tree-select"
              :select-params="{
                clearable: false,
                placeholder: '请选择',
              }"
              :tree-params="{
                'expand-on-click-node': false,
                'highlight-current': true,
                'filterable': true,
                props: {
                  value: 'orgId',
                  label: 'orgName',
                },
                data: treeData,
              }"
            />
          </el-form-item>
          <el-form-item label="电话:" prop="uphone">
            <el-input v-model.trim="temp.uphone" clearable :maxlength="15" />
          </el-form-item>
          <el-form-item label="显示顺序:" prop="showIndex">
            <el-input-number v-model="temp.showIndex" :min="1" clearable />
          </el-form-item>
          <el-form-item class="block" label="数据权限:" prop="orgScope">
            <el-radio-group v-model="temp.orgScope">
              <el-radio :label="1">不限</el-radio>
              <el-radio :label="2">本部门及下属部门</el-radio>
              <el-radio :label="3">本部门</el-radio>
              <el-radio :label="4">自定义</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item
            v-if="temp.orgScope === 4"
            class="block"
            :label="' '"
            prop="scopeOrgSNNo"
          >
            <el-tree-select
              v-model="temp.scopeOrgSNNo"
              class="tree-select"
              :clearable="false"
              :select-params="{
                placeholder: '请选择',
              }"
              :tree-params="{
                'expand-on-click-node': false,
                'highlight-current': true,
                'filterable': true,
                props: {
                  value: 'orgSNNo',
                  label: 'orgName',
                  disabled: 'disabled',
                },
                data: treeData,
              }"
              @node-click="selectScopeTreeChange"
            />
          </el-form-item>
          <el-form-item label="校验Mac1:" prop="scopeMac">
            <el-input v-model.trim="temp.scopeMac" clearable />
          </el-form-item>
          <el-form-item label="校验Host:" prop="checkHost">
            <el-input v-model.trim="temp.checkHost" clearable />
          </el-form-item>
          <el-form-item label="校验Mac2:" prop="scopeMac2">
            <el-input v-model.trim="temp.scopeMac2" clearable />
          </el-form-item>
          <el-form-item label="校验Mac3:" prop="scopeMac3">
            <el-input v-model.trim="temp.scopeMac3" clearable />
          </el-form-item>
          <el-form-item class="block" label="员工号:" prop="userWorkerCode">
            <el-input v-model.trim="temp.userWorkerCode" clearable :maxlength="30" />
          </el-form-item>
          <el-form-item class="block" label="地址:" prop="uaddress">
            <el-input v-model.trim="temp.uaddress" clearable :maxlength="100" />
          </el-form-item>
          <el-form-item
            label="备注:"
            prop="remark"
            class="block"
            :maxlength="200"
            show-word-limit
          >
            <el-input
              v-model.trim="temp.remark"
              type="textarea"
              :rows="3"
              maxlength="255"
              show-word-limit
            />
          </el-form-item>
        </el-form>
      </el-tab-pane>
      <el-tab-pane label="扩展信息" name="addition">
        <el-form
          ref="additionForm"
          class="form"
          :rules="rules"
          :model="additionData"
          label-position="right"
          label-width="90px"
        >
          <el-form-item label="证件类型" prop="codeType">
            <el-select
              v-model="additionData.codeType"
              placeholder="请选择"
              style="width: 100%;"
              clearable
            >
              <el-option
                v-for="item in codeTypeMap"
                :key="item.value"
                :label="item.desc"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="证件编号:" prop="codeNum">
            <el-input v-model.trim="additionData.codeNum" clearable :maxlength="30" />
          </el-form-item>
          <el-form-item label="到期日期:" prop="endTime">
            <el-date-picker
              v-model="additionData.endTime"
              type="date"
              placeholder="选择日期"
              style="width: 100%;"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" size="mini" @click="addCert">添加</el-button>
          </el-form-item>
        </el-form>
        <lb-table
          ref="lbTable"
          v-loading="$loadingPlugin.fetchData"
          border
          element-loading-text="加载中"
          :column="tableData.column"
          :data="tableData.data"
          :total="tableData.total"
          :page-size="5"
          :height="200"
          pagination
          @fetch="fetchData"
        />
      </el-tab-pane>
    </el-tabs>
    <div v-show="activeName === 'basic'" slot="footer" class="dialog-footer">
      <el-button @click="visible = false"> 取消 </el-button>
      <el-button :loading="$loadingPlugin.saveBasic" type="primary" @click="saveBasic">
        {{ type === "add" ? "下一步" : "保存" }}
      </el-button>
    </div>
    <div v-show="activeName === 'addition'" slot="footer" class="dialog-footer">
      <el-button @click="visible = false"> 取消 </el-button>
      <el-button :loading="$loadingPlugin.success" type="primary" @click="success">
        确定
      </el-button>
    </div>
    <cert-detail ref="certDetail" />
  </el-dialog>
</template>

<script>
  import {
    querySaveUserBasicInfo,
    saveUserCertInfo,
    deleteUserCertInfo,
    queryOrgCode,
    userQueryCertList,
    saveBatchUserCert
  } from '@/api'
  import { mapGetters } from 'vuex'
  import moment from 'dayjs'
  import { formatColumnMap, parseTime } from '@/utils'
  import CertDetail from './CertDetail'

  export default {
    name: 'add-user',
    components: {
      CertDetail
    },
    props: {
      treeData: {
        type: Array,
        required: true
      },
      userTypeMap: {
        type: Array,
        required: true
      }
    },
    data() {
      const validatePwd = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请输入初始密码'))
        } else {
          if (value !== '') {
            const reg = /^[\w]{6,15}$/
            if (!reg.test(value)) {
              callback(new Error('密码必须是6-15位的字母或数字'))
            }
          } else {
            callback()
          }
          callback()
        }
      }
      const validScopeMac = (rule, value, callback) => {
        if (value !== '') {
          const reg = /^[\d]{1,3}.[\d]{1,3}.[\d]{1,3}.[\d]{1,3}:[\d]{4,5}$/gi
          if (!reg.test(value)) {
            callback(new Error('请输入正确的校验Mac地址'))
          }
        } else {
          callback()
        }
      }
      const validCheckHost = (rule, value, callback) => {
        if (value !== '') {
          const reg = /^[\d]{1,3}.[\d]{1,3}.[\d]{1,3}.[\d]{1,3}:[\d]{4,5}$/gi
          if (!reg.test(value)) {
            callback(new Error('请输入正确的校验Host地址[IP:端口]'))
          }
        } else {
          callback()
        }
      }
      return {
        visible: false,
        type: 'add',
        activeName: 'basic',
        codeTypeMap: [
          { value: 1, desc: '身份证' },
          { value: 2, desc: '特种设备作业人员证' },
          { value: 3, desc: '其他' },
          { value: 4, desc: '备用1' }
        ],
        currentOrg: null, // 用户所属的机构
        scopeOrg: null, // 数据权限下的所属机构
        temp: {
          userCode: '',
          pwd: '',
          userName: '',
          utype: [],
          usex: 1,
          orgId: '',
          uphone: '',
          showIndex: 999,
          orgScope: '',
          scopeOrgSNNo: '',
          scopeMac: '',
          checkHost: '',
          scopeMac2: '',
          scopeMac3: '',
          userWorkerCode: '',
          uaddress: '',
          remark: '',
          ustatus: 1 // 未知
        },
        savedBasicInfo: null,
        additionData: {
          codeType: '',
          codeNum: '',
          endTime: ''
        },
        rules: {
          pwd: [
            { required: true, message: '请输入初始密码', trigger: 'change' },
            { validator: validatePwd, trigger: 'blur' }
          ],
          userName: [{ required: true, message: '请输入用户名称', trigger: 'change' }],
          utype: [{ required: true, message: '请选择用户类型', trigger: 'change' }],
          orgScope: [{ required: true, message: '请选择数据权限', trigger: 'change' }],
          scopeMac: [{ validator: validScopeMac, trigger: 'change' }],
          scopeMac2: [{ validator: validScopeMac, trigger: 'change' }],
          scopeMac3: [{ validator: validScopeMac, trigger: 'change' }],
          checkHost: [{ validator: validCheckHost, trigger: 'change' }],
          codeType: [{ required: true, message: '请选择证件类型', trigger: 'change' }],
          codeNum: [{ required: true, message: '请输入证件编号', trigger: 'blur' }]
        },
        tableData: {
          total: 0,
          data: [],
          column: [
            {
              prop: 'dictionaryId',
              label: '证件类型',
              render: (h, { row }) => (
              <span>
                {row.dictionaryId &&
                  formatColumnMap(this.codeTypeMap, 'value', row.dictionaryId, 'desc')}
              </span>
            )
            },
            {
              prop: 'codeNum',
              label: '证件编号'
            },
            {
              prop: 'endTime',
              label: '到期日期',
              render: (h, { row }) => (
              <el-link>{row.endTime && parseTime(row.endTime, '{y}-{m}-{d}')}</el-link>
            )
            },
            {
              label: '操作',
              align: 'center',
              fixed: 'right',
              width: 150,
              render: (h, scope) => {
                return scope.row.saved ? (
                <div>
                  <el-button
                    type='primary'
                    size='mini'
                    onClick={() => this.viewRow(scope)}
                  >
                    查看
                  </el-button>
                  <el-button size='mini' type='danger' onClick={() => this.delRow(scope)}>
                    删除
                  </el-button>
                </div>
                  ) : (
                <div>
                  <el-button
                    type='primary'
                    size='mini'
                    onClick={() => this.saveRow(scope)}
                  >
                    保存
                  </el-button>
                  <el-button size='mini' type='danger' onClick={() => this.delRow(scope)}>
                    删除
                  </el-button>
                </div>
                )
              }
            }
          ]
        }
      }
    },
    computed: {
      ...mapGetters(['userInfo', 'orgList']),
      filterUserTypeMap: function() {
        return this.userTypeMap.filter(item => item.value !== 1)
      }
    },
    methods: {
      async open(temp, org) {
        this.temp.scopeOrgSNNo = this.treeData[0].orgSNNo
        return new Promise((resolve) => {
          this.resolve = resolve
          this.visible = true
          if (org) this.currentOrg = org
          if (!temp) {
            this.type = 'add'
          } else {
            this.type = 'edit'
            this.temp = Object.assign(this.temp, temp, {
              utype: this.userTypeMap
                .filter((item, index) => (temp.utype >> index) & 1)
                .map((it) => it.value)
            })
            this.savedBasicInfo = temp
            if (temp.scopeOrgId) {
              this.scopeOrg = this.orgList.find((item) => item.orgId === temp.scopeOrgId)
              this.temp.scopeOrgSNNo = this.scopeOrg.orgSNNo
            }
          }
        })
      },
      // 获取用户编码
      async getOrgCode() {
        const res = await queryOrgCode({
          codeType: 7
        })
        this.temp.userCode = res.data
      },
      // 选择数据权限下的所属机构
      selectScopeTreeChange(value) {
        this.scopeOrg = value
      },
      // 下一步
      async saveBasic() {
        const valid = await this.$refs.dataForm.validate()
        if (!valid) return
        const params = {
          userId: this.type === 'add' ? 0 : this.temp.userId,
          userName: this.temp.userName,
          usex: this.temp.usex,
          ustatus: this.temp.ustatus,
          uphone: this.temp.uphone,
          uaddress: this.temp.uaddress,
          userWorkerCode: this.temp.userWorkerCode,
          remark: this.temp.remark,
          scopeMac: this.temp.scopeMac,
          scopeMac2: this.temp.scopeMac2,
          scopeMac3: this.temp.scopeMac3,
          checkHost: this.temp.checkHost,
          showIndex: this.temp.showIndex,
          orgScope: this.temp.orgScope
        }
        if (this.temp.orgScope === 4) {
          if (this.scopeOrg) {
            params.scopeOrgId = this.scopeOrg.orgId
            params.scopeOrgName = this.scopeOrg.orgName
            params.scopeOrgSNNo = this.scopeOrg.orgSNNo
          }
        }
        if (this.type === 'add') {
          params.userCode = this.temp.userCode
          params.pwd = this.temp.pwd
          params.orgId = this.currentOrg.orgId
          params.orgSNNo = this.currentOrg.orgSNNo
          params.orgName = this.currentOrg.orgName
          params.scopeOrgId = this.currentOrg.orgId
          params.scopeOrgName = this.currentOrg.orgName
          params.scopeOrgSNNo = this.currentOrg.orgSNNo
        }
        if (this.type === 'edit') {
          const org = this.orgList.find((item) => item.orgId === this.temp.orgId)
          params.orgId = org.orgId
          params.orgSNNo = org.orgSNNo
          params.orgName = org.orgName
        }
        params.utype = this.temp.utype.reduce((pre, cur) => pre + cur, 0)
        const res = await querySaveUserBasicInfo({ json: params })
        if (this.type === 'edit') {
          this.resolve()
          this.visible = false
          return
        }
        if (res.data) {
          this.savedBasicInfo = res.data
          this.activeName = 'addition'
        }
      },
      async fetchData({ currentPage, pageSize }) {
        if (this.type === 'add') return
        const query = {
          currentPage,
          pageSize,
          userId: this.temp.userId
        }
        const res = await userQueryCertList(query)
        this.tableData.data = res.data.rows.map((item) => {
          return {
            saved: true,
            ...item
          }
        })
        if (currentPage === 1) this.tableData.total = res.data.total
      },
      // 添加证件
      async addCert() {
        const valid = await this.$refs.additionForm.validate()
        if (!valid) return
        if (!this.savedBasicInfo) {
          this.$message.warning('请先保存用户基本信息')
          return
        }
        if (
          this.tableData.data.some(
            (item) =>
              item.dictionaryId === this.additionData.codeType &&
              item.codeNum === this.additionData.codeNum
          )
        ) {
          this.$message.warning('添加同类型的用户证件，证件编号不能一样')
          return
        }
        const row = {
          saved: false,
          id: 0,
          dictionaryId: this.additionData.codeType,
          keyName: this.codeTypeMap.find(
            (item) => item.value === this.additionData.codeType
          ).desc,
          codeNum: this.additionData.codeNum,
          userId: this.savedBasicInfo.userId
        }
        if (this.additionData.endTime) {
          row.endTime = moment(this.additionData.endTime).format('YYYY-MM-DD')
        }
        this.tableData.data.push(row)
      },
      // 查看行
      async viewRow(scope) {
        await this.$refs.certDetail.open(scope.row)
      },
      // 保存行
      async saveRow(scope) {
        const res = await saveUserCertInfo(scope.row)
        this.$set(scope.row, 'id', res.data)
        this.$set(scope.row, 'saved', true)
      },
      // 删除行
      delRow(scope) {
        const index = scope.$index
        if (scope.row.saved) {
          this.$confirm('删除客户证件类型不可恢复，确定要执行吗？', '提示', {
            type: 'warning'
          }).then(() => {
            const loading = this.$message({
              message: '正在删除',
              duration: 0,
              iconClass: 'el-icon-loading'
            })
            deleteUserCertInfo({ id: scope.row.id }).then(() => {
              this.tableData.data.splice(index, 1)
              this.$notify({
                title: '提示',
                message: '删除成功',
                type: 'success',
                duration: 2000
              })
            }).finally(() => {
              loading.close()
            })
          })
        } else {
          this.$confirm('删除客户证件类型不可恢复，确定要执行吗？', '提示', {
            type: 'warning'
          }).then(() => {
            this.tableData.data.splice(index, 1)
          })
        }
      },
      async success() {
        await saveBatchUserCert(this.tableData.data)
        this.resolve()
        this.visible = false
      },
      reset() {
        this.type = 'add'
        this.activeName = 'basic'
        this.temp = {
          userCode: '',
          pwd: '',
          userName: '',
          utype: [],
          usex: 1,
          orgId: '',
          uphone: '',
          showIndex: 999,
          orgScope: '',
          scopeOrgSNNo: '',
          scopeMac: '',
          checkHost: '',
          scopeMac2: '',
          scopeMac3: '',
          userWorkerCode: '',
          uaddress: '',
          remark: '',
          ustatus: 1 // 未知
        }
        this.additionData = {
          codeType: '',
          codeNum: '',
          endTime: ''
        }
        this.currentOrg = null
        this.scopeOrg = null
        this.savedBasicInfo = null
        this.tableData.data = []
        this.$nextTick(() => {
          this.$refs.dataForm && this.$refs.dataForm.clearValidate()
          this.$refs.additionForm && this.$refs.additionForm.clearValidate()
        })
      }
    }
  }
</script>

<style lang="scss" scoped>
.tree-select {
  width: 100%;
  & /deep/ .el-tree-select-input {
    width: 100%;
  }
}
.form {
  display: flex;
  flex-wrap: wrap;
  & /deep/ .el-form-item {
    width: 50%;
    padding-right: 10px;
    .el-form-item__content > .el-select {
      width: 100%;
    }
  }
  .block {
    width: 100%;
  }
}

.addUser {
  /deep/.el-input-group__append {
    button.el-button {
      color: #01999f;
      background: #e6f5f5;
      // border-color: #99d6d9;
    }
    button.el-button:hover {
      // border-color: #01999f;
      color: #fff;
      background: #01999f;
    }
  }
}
</style>
